package com.oceansoft.mobile.weixin.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	public static final String PATTERN_STANDARD = "yyyy-MM-dd HH:mm:ss";
	public static final String PATTERN_DATE = "yyyy-MM-dd";

	public static String getUploadDate(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(new Date());
	}

	/**
	 * 获取当前时间的字符格式
	 * @return
     */
	public static String getCurrentDateTime(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}
	/**
	 * 获取某一天的开始时间戳和结束时间戳
	 * 列如：2014-05-09 00:00:00 - 2014-05-09 23:59:59
	 */
	public static Long[] getDayTimestamp(Date date){
		if(null==date)
			return null;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String day = sdf.format(date);
		Long[] timestamp = {0l,0l};
		
		try {
			timestamp[0]=(getFormatDate(day + " 00:00:00")).getTime();
			timestamp[1]=(getFormatDate(day + " 23:59:59")).getTime();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return timestamp;
	}
	
	/**
	 * 根据时间字符串获取其Date类型 
	 */
	public static Date getFormatDate(String date){
		if(null==date)
			return null;
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 昨天
	 * @return
	 */
	public static Date getYesterdayDate(){
		Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        return cal.getTime();
	}

	public static String date2String(Date date, String pattern) {
		if (date == null) {
			date = new Date();
            throw new IllegalArgumentException("timestamp null illegal");
		}
		if (pattern == null || pattern.equals("")) {
			pattern = PATTERN_STANDARD;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	public static Date string2Date(String strDate, String pattern) {
		if (strDate == null || strDate.equals("")) {
//            return new Date();
			throw new RuntimeException("string date is null");
		}
		if (pattern == null || pattern.equals("")) {
			pattern = DateUtil.PATTERN_DATE;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
//            return new Date();
			throw new RuntimeException(e);
		}
	}

}
















